import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式：light | dark
  const themeMode = ref(localStorage.getItem('theme-mode') || 'light')
  
  // 主题颜色
  const themeColor = ref(localStorage.getItem('theme-color') || '#409EFF')
  
  // Element Plus主题颜色映射
  const themeColors = {
    '#409EFF': 'default',
    '#67C23A': 'success',
    '#E6A23C': 'warning',
    '#F56C6C': 'danger',
    '#909399': 'info'
  }
  
  // 设置主题模式
  const setThemeMode = (mode) => {
    themeMode.value = mode
    localStorage.setItem('theme-mode', mode)
    applyTheme()
  }
  
  // 设置主题颜色
  const setThemeColor = (color) => {
    themeColor.value = color
    localStorage.setItem('theme-color', color)
    applyTheme()
  }
  
  // 切换主题模式
  const toggleThemeMode = () => {
    const newMode = themeMode.value === 'light' ? 'dark' : 'light'
    setThemeMode(newMode)
  }
  
  // 应用主题
  const applyTheme = () => {
    // 应用明暗主题
    if (themeMode.value === 'dark') {
      document.body.classList.add('dark-theme')
      document.body.classList.remove('light-theme')
    } else {
      document.body.classList.add('light-theme')
      document.body.classList.remove('dark-theme')
    }
    
    // 应用主题颜色
    const root = document.documentElement
    root.style.setProperty('--el-color-primary', themeColor.value)
    
    // 根据主题颜色生成其他颜色变体
    // 这里简化处理，实际项目中可能需要更复杂的颜色算法
    const colorMap = {
      '#409EFF': { light: '#409EFF', dark: '#409EFF' },
      '#67C23A': { light: '#67C23A', dark: '#67C23A' },
      '#E6A23C': { light: '#E6A23C', dark: '#E6A23C' },
      '#F56C6C': { light: '#F56C6C', dark: '#F56C6C' },
      '#909399': { light: '#909399', dark: '#909399' }
    }
    
    const currentColor = colorMap[themeColor.value] || colorMap['#409EFF']
    root.style.setProperty('--el-color-primary', 
      themeMode.value === 'dark' ? currentColor.dark : currentColor.light)
  }
  
  // 初始化主题
  const initTheme = () => {
    applyTheme()
  }
  
  return {
    themeMode,
    themeColor,
    themeColors,
    setThemeMode,
    setThemeColor,
    toggleThemeMode,
    initTheme
  }
})